import { $, formatMinute, updateFloat } from "../../utils";
import { IScheduleTask } from "../node";
import { RedPacket } from "./RedPacket";
declare const runtime: any;

export class KwaiNebulaQiangBaoSheduleTask implements IScheduleTask {
    time: number = 1000 * 60 * 60;
    title: string = `【快手极速抢包】`;
    isRuning: boolean = false;
    check(): boolean {
        if (this.redPackets.length === 0) {
            return true;
        }
        if (this.redPackets.find(red => [6, 2, 0].includes(red.type))) {
            return false;
        }
        return true;
    }
    start(): void {
        if (this.isRuning) {
            updateFloat({ toast: `${this.title}已经执行` })
            return;
        }
        this.isRuning = true;
        updateFloat({ toast: `正在执行${this.title}任务`, currentTask: this.title })
        const latestActivity = runtime.info.latestActivity;
        if (['zd4.q', 'n27.a', 'u27.a', 'gqc.a', 'com.kuaishou.live.basic.dialog.LiveDialogContainerFragment$b'].includes(latestActivity)) {
            back();
            sleep(2000)
        }
        sleep(1000 * 10)
        this.joinRedPacket()
    }
    private maxTime: number = 20 * 1000;
    private joinRedPacket() {
        let time = new Date().getTime()
        updateFloat({ currentResult: `正在检查房间状态` })
        const node = selector().idEndsWith("live_red_packet_status_text").visibleToUser(true).findOne(this.maxTime)
        this.maxTime = ((new Date().getTime() - time) + this.maxTime) / 2;
        if (node) {
            $.tryClickButton(node)
            updateFloat({ currentResult: `成功打开红包弹框` })
            this.joinAndWaitRedPacket()
        } else {
            this.maxTime + 1000;
            updateFloat({ currentResult: `此房间暂无红包` })
            return;
        }
    }
    redPackets: RedPacket[] = [];
    private joinAndWaitRedPacket() {
        const viewPager = selector().classNameEndsWith('ViewPager').visibleToUser(true).findOne()
        const children = viewPager.children()
        updateFloat({ currentResult: `共有${children.length}个红包` })
        let joinCount: number = 0;
        for (let index = 0; index < children.length; index++) {
            const child = children[index];
            let texts: string[] = [];
            const redPacket = new RedPacket();
            this.filterEachChildren(child, (node) => {
                let text = node.text()
                if (text) {
                    texts.push(text)
                    if (text === `开金粉 抢红包`) {
                        redPacket.setJoinButton(node)
                    }
                    if (text === `去评论`) {
                        redPacket.setJoinButton(node)
                    }
                    if (text === `抢红包`) {
                        redPacket.setJoinButton(node)
                    }
                    if (text === `点我抢红包`) {
                        redPacket.setJoinButton(node)
                    }
                }
                return false;
            })
            redPacket.setText(texts.join(' '))
            if (redPacket.join()) {
                joinCount += 1;
                this.redPackets.push(redPacket)
            }
        }
        if (joinCount > 0) {
            updateFloat({ currentResult: `已参加${joinCount}个红包，等待开奖` })
            this.waitOpen();
        } else {
            updateFloat({ currentResult: `没有满足条件的红包` })
        }
    }
    private toRoom() {
        let onlineNode = selector().idEndsWith('live_audience_count_text').visibleToUser(true).findOne(3000)
        while (!onlineNode) {
            back();
            sleep(3000)
        }
    }
    private waitOpen() {
        let text = selector().textMatches(/.*?后开奖/).visibleToUser(true).findOnce()
        while (text) {
            sleep(1000)
            updateFloat({ currentResult: text.text() })
            text = selector().textMatches(/.*?后开奖/).visibleToUser(true).findOnce()
        }
        sleep(15 * 1000)
        this.toRoom();
        this.redPackets = [];
        if (this.isRuning) {
            this.joinRedPacket()
        }
    }
    private filterEachChildren(node: UiObject, filter: (node: UiObject) => boolean) {
        const children = node.children();
        const list: UiObject[] = [];
        children.map(child => {
            if (filter(child)) {
                list.push(child)
            } else {
                list.push(...this.filterEachChildren(child, filter))
            }
        });
        return list;
    }
    stop(): void {
        this.isRuning = false;
        updateFloat({ toast: `${this.title}任务执行结束`, currentTask: this.title })
        this.toHome();
    }

    toHome() {
        let homeNode = selector().text('首页').visibleToUser(true).findOne(3000)
        while (!homeNode) {
            back();
            sleep(3000)
            $.tryClickButton(selector().textMatches('退出直播间|退出').findOne(3000))
        }
        home();
        sleep(3000)
    }
}